import { useState, useEffect, useRef } from "react";
// import { CommonModal } from "@/views/components/CommonModal";
import { CommonField } from "@/pages/OrderModule/common/components/CommonForm";
import ProductSynchronizationUpdateModal from "../../ProductSynchronizationUpdateModal";
// import { CommonForm } from "@/pages/OrderModule/common/components/CommonForm";
// import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
// import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
// import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import {
	PrefixPlaceholder,
	Input,
	Select,
	PreInputNumber,
	CommonInput,
	CommonInputNumber
} from "@/views/components/PrefixPlaceholder";
import TableEditForm from "./TableEditForm";
// import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import CommonImgsLoad from "@/components/CommonImgsLoad";
import IconFont from "@/components/IconFont";
import ImageErrorModal from "./ImageErrorModal";
import {
	Button,
	Col,
	Collapse,
	Form,
	// Input,Select,
	Row,
	Tooltip,
	Checkbox,
	Space,
	Modal,
	Anchor,
	Upload,
	Radio,
	message,
	Tabs,
	Drawer
} from "antd";
import AttrList from "./AttrList";
import { useGoodsColumns } from "./goodsColumns";
import { ContainerTwoTone } from "@ant-design/icons";
// import HelpInfo from "@/views/components/HelpInfo";
// import { PlusOutlined } from "@ant-design/icons";
import { SPU_STATUS, YES_NO_NUM_STATUS } from "@/views/utils/constant";
import AttrClassifyModal from "./AttrClassifyModal";
import CommonDrawer from '@/components/CommonDrawer';
import { getGoodsAttribute, goodsSpuSubmit } from "../../../../service";
import { cloneDeep } from "lodash";
import { useArchorList } from "./archorList";
import { useAnchor } from "@/pages/OrderModule/common/hooks/useAnchor";
import { DoubleLeftOutlined } from "@ant-design/icons";
import Style from "./index.module.less";
const ARCHOR_LIST_MAP = {
	basicInformation: 0, // 基础信息
	imageAttachment: 1, // 图片附件
	attributes: 2, // 商品属性
	colorSpecifications: 3, // 颜色尺码
	otherSettings: 4 // 其他设置
};

const defaultGoodsData = () => {
	return {
		key: Math.random() + "",
		image: null,
		skuCode: null,
		colour: null,
		specs: null,
		retailPrice: null,
		costPrice: null,
		purchasePrice: null,
		tagPrice: null,
		weight: null,
		productIngredients: null,
		customAttribute: null
	};
};

const SpuViewModal = props => {
	const [form] = Form.useForm();
	const [type, setType] = useState();
	// 商品详情数据
	const { details, onCancel, fetchList } = props;
	const isEdit = !!details?.id;

	const title = (isEdit ? "编辑" : "新增") + "商品（款）";
	// 弹窗相关
	const [dialogName, setDialogName] = useState("");
	const [visible, setVisible] = useState(false);
	// 图片附件
	const goodsImage = details?.image;
	// 商品属性数据
	const [attrList, setAttrList] = useState([]);
	const [oldAttrList, setOldAttrList] = useState([]);
	const { goodsColumns } = useGoodsColumns({ defaultGoodsData, form, setDialogName, isEdit });
	// 针对颜色尺码list的相关操作
	const opera1Value = Form.useWatch("opera1", form);
	const opera2Value = Form.useWatch("opera2", form);
	const opera3Value = Form.useWatch("opera3", form);

	const [selectedRowKeys, setSelectedRowKeys] = useState([]);
	//商品信息同步更新列表
	const [goodSyncList, setGoodSyncList] = useState();

	// 锚点
	const archorList = useArchorList();
	const [tab, setTab] = useState(archorList[ARCHOR_LIST_MAP.basicInformation].key);
	const contentWrapperRef = useRef(null);
	const anchorItems = useRef({});
	const { currentAnchor, scrollToAnchor } = useAnchor(contentWrapperRef, anchorItems);

	useEffect(() => {
		archorList.forEach(item => {
			anchorItems.current[item.key] = document.getElementById(item.key);
		});
		if (!details?.id) {
			const obj = defaultGoodsData();
			form.setFieldsValue({
				goodsSku: [obj]
			});
		}
	}, []);

	// 监听用户选择创建几行sku
	useEffect(() => {
		const arr = [];
		for (let i = 0; i < opera1Value; i++) {
			arr.push(defaultGoodsData());
		}
		const goodsSkuList = form.getFieldValue("goodsSku") || [];
		form.setFieldsValue({
			goodsSku: [...goodsSkuList, ...arr]
		});
	}, [opera1Value]);
	// 监听用户清空/生成商品编码
	useEffect(() => {
		const goodsSkuList = form.getFieldValue("goodsSku") || [];
		if (goodsSkuList.length === 0) return;
		let arr = cloneDeep(goodsSkuList);
		const spuCodeValue = form.getFieldValue("spuCode")?.trim();
		arr = arr.map((item, index) => {
			// 如果有选中的数据，只赋值选中的数据,没有选数据就全部赋值
			if (selectedRowKeys.includes(item.key) || selectedRowKeys.length === 0) {
				return {
					...item,
					skuCode: opera2Value === "clear" ? null : item.skuCode || (spuCodeValue && `${spuCodeValue}-00${index + 1}`)
				};
			}
			return item;
		});
		form.setFieldsValue({
			goodsSku: arr
		});
	}, [opera2Value]);
	// 监听批量填充
	useEffect(() => {
		let goodsSkuList = form.getFieldValue("goodsSku") || [];
		if (goodsSkuList.length === 0) return;
		const formData = form.getFieldsValue();
		// 零售价
		let value = "";
		switch (opera3Value) {
			// 零售价
			case "retailPrice":
				value = formData.retailPrice;
				break;
			// 成本价
			case "costPrice":
				value = formData.costPrice;
				break;
			// 市场价
			case "tagPrice":
				value = formData?.attributes[attrList?.findIndex(item => item.attributeName == "市场价I吊牌价")]?.value || null;
				break;
			// 重量
			case "weight":
				value = formData.weight;
				break;
			// 图片
			case "image":
				value = formData.image;
				break;
			// 商品成分
			case "productIngredients":
				value = formData?.attributes[attrList.findIndex(item => item.attributeName == "商品成分")]?.value || null;
				break;
			// 自定义属性（暂无自定义属性）
			case "customAttribute":
				value = formData?.attributes[attrList.findIndex(item => item.attributeName == "自定义属性")]?.value || null;
				break;
			default:
				break;
		}

		const arr = goodsSkuList.map(item => {
			if (selectedRowKeys.includes(item.key) || selectedRowKeys.length === 0) {
				return {
					...item,
					[opera3Value]: value
				};
			}
			return item;
		});
		console.log(opera3Value, value, arr);
		form.setFieldsValue({
			goodsSku: arr
		});
	}, [opera3Value]);
	// 获取分类属性列表
	const getAttrList = async pre => {
		const { data, success } = await getGoodsAttribute();
		if (success) {
			const attributesList = data.map((item, index) => {
				// 输入框样式(1：下拉框 2：文本框)
				if (item.type === 1)
					item.options = item.attributeValue.split(",").map(val => {
						return {
							label: val,
							value: val
						};
					});

				// 判断编辑状态下需要赋值value
				// if (isEdit) {
				const obj = details?.attributes?.find(e => e.attributeName === item.attributeName) || {};
				item.value = obj?.attributeValue;
				// }
				return {
					...item,
					value: (pre && pre[index]?.value) || item.value
				};
			});
			setAttrList([...attributesList]);
			form.setFieldsValue({
				// 判断是否编辑
				attributes: attributesList
			});
		}
	};
	useEffect(() => {
		getAttrList();
		if (isEdit) {
			form.setFieldsValue({
				goodsSku: details.goodsSku
			});
		}
	}, []);
	// 监听分类属性列表变化，筛选出启用的数据
	useEffect(() => {
		// 打开分类属性需要把商品属性存起来
		if (dialogName === "AttrClassifyModal") {
			// console.log("dialogName", dialogName);
			// console.log(form.getFieldValue("attributes"));
			setOldAttrList(form.getFieldValue("attributes"));
		}
	}, [dialogName]);

	useEffect(() => {
		if (details) {
			console.log("you");
		} else {
			console.log("wu");
		}
	}, [details]);
	// 图片上传失败
	const handleError = (err, failed) => {
		// console.log("file upload error", err, failed);
		if (!err.isLt2M) {
			setDialogName("ImageErrorModal");
		}
	};
	const remove = (record, index) => {
		const arr = cloneDeep(form.getFieldValue("goodsSku"));
		arr.splice(index, 1);
		form.setFieldsValue({
			goodsSku: arr
		});
	};

	//图片上传回调手动更新表单值
	const handleUploadImg = val => {
		// console.log("上传图片路径", val);
		form.setFieldsValue({
			image: val
		});
	};
	// 创建
	function handleOk(type, checkSku = true) {
		form
			.validateFields()
			.then(val => {
				const API_DATA = form.getFieldsValue();

				if (!API_DATA?.goodsSku || API_DATA?.goodsSku?.length === 0) {
					return Modal.error({ content: "请先添加颜色尺码", centered: true });
				}
				// 如果是跑量商品，SKU只能填写一个
				if (API_DATA.runningVolumeStatus && API_DATA?.goodsSku.length !== 1) {
					return message.warning({ content: "跑量商品仅可设置一个" });
				}
				// 判断-商品信息同步更新
				if (checkSku) {
					console.log("API_DATA.goodsSku", API_DATA.goodsSku);
					const diffList = goodsInfoSyncUpdata(API_DATA);
					if (diffList.filter(e => e.diff).length) {
						setGoodSyncList(diffList);
						setDialogName("ProductSynchronizationUpdate");
						return;
					}
				}
				API_DATA.attributes = attrList.map((item, index) => {
					const data = {
						status: item.status,
						type: item.type,
						attributeId: item.id,
						attributeName: item.attributeName || null,
						attributeValue: API_DATA?.attributes[index]?.value ?? null
					};
					// 编辑时获取对应的id赋值，否则会被后端判断成新增
					let id = null;
					if (isEdit) {
						const list = details?.attributes || [];
						const obj = list.find(e => e.attributeId === item.attributeId);
						id = obj?.id || null;
					}
					if (id) data.id = id;
					return data;
				});

				isEdit ? (API_DATA.id = details.id) : null;
				goodsSpuSubmit(API_DATA).then(res => {
					if (res.success) {
						// 不关闭窗口
						message.success("创建成功");
						if (type === "save") {
							form.resetFields();
						} else {
							onCancel();
							fetchList();
						}
					}
				});
			})
			.catch(error => {
				setTimeout(() => {
					console.log("error", error);
					// 核心代码
					const errorList = document.querySelectorAll(".ant-form-item-has-error") || [];
					console.log("errorList", errorList);
					// 由于校验失败ant会自动给失败表单项添加类名，直接获取即可
					if (errorList.length) {
						errorList[0]?.scrollIntoView({
							block: "center",
							behavior: "smooth"
						});
					}
				}, 100);
			});
	}
	// 商品信息同步更新
	function goodsInfoSyncUpdata(form) {
		console.log(form);
		// 基础信息
		const Map = {
			retailPrice: "零售价",
			costPrice: "成本价",
			weight: "重量"
		};
		// 商品属性
		const attrMap = {
			市场价I吊牌价: "tagPrice",
			商品成分: "productIngredients",
			自定义属性: "customAttribute"
		};
		// 收集与spu不一致的数据
		let diffArr = [];
		Object.keys(Map).forEach(key => {
			console.log(Map[key], form[key]);
			diffArr.push({
				value: form[key],
				name: Map[key],
				prop: key,
				// 是否有差异
				diff: false
			});
		});
		// 获取对应的商品属性
		const attrList = (form.attributes || []).filter(e => Object.keys(attrMap).includes(e.attributeName));
		attrList.forEach(item => {
			diffArr.push({
				value: item.value,
				name: item.attributeName,
				prop: attrMap[item.attributeName],
				// 是否有差异
				diff: false
			});
		});
		console.log("spu 的信息：", diffArr);
		// spu没有值的数据不用比较
		diffArr = diffArr.filter(item => item.value != null);
		// 查询差异的sku行,
		diffArr.forEach(item => {
			// 查找数据中的值是否和spu的相等
			item.diff = (form?.goodsSku || []).some(e => {
				// console.log(item.prop, item.name);
				// console.log(e[item.prop], item.value, e[item.prop] != item.value);
				return e[item.prop] != item.value;
			});
		});
		console.log("结束：", diffArr);
		return diffArr.filter(e => e.diff);
	}

	return (
		<CommonDrawer
			title={title}
			open={true}
			width="80%"
			// zIndex={1010}
			onClose={onCancel}
			footer={
				<Row justify="end">
					<Col>
						<Space>
							<Button size="middle" onClick={onCancel}>
								取消
							</Button>
							{!isEdit && (
								<Button
									size="middle"
									onClick={() => {
										setType("save");
										handleOk("save");
									}}
								>
									保存并继续
								</Button>
							)}
							<Button
								size="middle"
								type="primary"
								onClick={() => {
									setType();
									handleOk();
								}}
							>
								{isEdit ? "保存" : "创建"}
							</Button>
						</Space>
					</Col>
				</Row>
			}
		>
			<div className="flex" style={{ flexDirection: "column", height: "100%" }}>
				<div className={Style.archor_tab + " rule-reset"}>
					<Tabs
						activeKey={tab}
						onChange={val => {
							setTab(val);
							scrollToAnchor(val);
						}}
					>
						{archorList.map(item => (
							<Tabs.TabPane tab={item.title} key={item.key}></Tabs.TabPane>
						))}
					</Tabs>
				</div>
				<div className={Style.detail_inner} ref={contentWrapperRef}>
					<Form
						form={form}
						initialValues={{
							...details,
							goodsImage,
							goodsSku: details?.goodsSku || []
						}}
					>
						<Collapse
							defaultActiveKey={Object.keys(ARCHOR_LIST_MAP)}
							ghost
							expandIcon={({ isActive }) => (
								<DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: "16px", color: "#4E5969" }} />
							)}
							expandIconPosition="end"
							className={Style["reset-collapse"]}
						>
							<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.basicInformation].render()} key="basicInformation">
								<div className={Style.container}>
									<Form.Item
										name="spuName"
										rules={[{ required: true, message: "请输入商品名称" }]}
										className={Style.item}
										style={{ width: "calc(40% - 7px)" }}
									>
										<CommonInput placeholder="商品名称" aria-required showCount maxLength={100} />
									</Form.Item>
									<Row gutter={6} className={Style.item}>
										<Col span={23}>
											<Form.Item name="spuCode" rules={[{ required: true, message: "请输入款式编码" }]}>
												<CommonInput placeholder="款式编码" aria-required showCount maxLength={64} style={{ marginRight: 10 }} />
											</Form.Item>
										</Col>
										<Col span={1}>
											<Tooltip
												placement="bottomLeft"
												title={
													<>
														修改款式编码后，如果新款式编码资料已存在，则原款式编码资料被删除，如新款式编码不存在，则按原款式编码资料转移至新款式编码，请知悉
													</>
												}
											>
												<IconFont type="iconwenhao" />
											</Tooltip>
										</Col>
									</Row>
									<Form.Item name="spuAbbreviation" rules={[{ max: 40, message: "超出字符限制" }]} className={Style.item}>
										<CommonField
											Component={Input}
											props={{
												showCount: true,
												maxLength: 40,
												placeholder: "商品简称"
											}}
										/>
									</Form.Item>
									<Form.Item className={Style.item}></Form.Item>
									<Form.Item name="costPrice" rules={[{ required: true, message: "请输入成本价" }]} className={Style.item}>
										<CommonInputNumber min={0} placeholder="成本价" precision={2} controls={false} style={{ width: "100%" }} />
									</Form.Item>
									<Form.Item name="retailPrice" className={Style.item}>
										<CommonInputNumber min={0} placeholder="零售价" precision={2} controls={false} />
									</Form.Item>
									{/* <Form.Item name="purchasePrice">
										<CommonInput placeholder="采购价" disabled />
									</Form.Item> */}
									<Form.Item name="weight" className={Style.item}>
										<CommonInputNumber
											min={0}
											placeholder="重量"
											addonAfter="kg"
											precision={2}
											controls={false}
											style={{ width: "100%" }}
										/>
									</Form.Item>
								</div>
							</Collapse.Panel>
							<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.imageAttachment].render()} key="imageAttachment">
								<Row gutter={[12, 6]}>
									<Col span={24}>
										<Form.Item valuePropName="fileList" name="image">
											<CommonImgsLoad
												img={goodsImage}
												size={1}
												handleOk={handleUploadImg}
												// handleError={handleError}
												// zIndex={1001}
												antPreview={true}
												upLoadText="请上传"
											/>
										</Form.Item>
									</Col>
								</Row>
							</Collapse.Panel>
							<Collapse.Panel
								header={archorList[ARCHOR_LIST_MAP.attributes].render()}
								key="attributes"
								style={{ position: "relative" }}
							>
								<Button
									type="text"
									onClick={() => setDialogName("AttrClassifyModal")}
									style={{ position: "absolute", right: 0, top: "12px" }}
								>
									<ContainerTwoTone style={{ marginRight: 5 }} />
									维护分类属性
								</Button>
								<div>
									<Row gutter={[12, 6]}>
										<AttrList name="attributes" initialValue={attrList} />
									</Row>
								</div>
							</Collapse.Panel>
							<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.colorSpecifications].render()} key="colorSpecifications">
								<div className={Style.container}>
									<Form.Item name="opera1" className={Style.item}>
										<CommonField
											Component={Select}
											props={{
												placeholder: "商品尺码",
												options: [
													{ label: "添加一行", value: 1 },
													{ label: "添加二行", value: 2 },
													{ label: "添加五行", value: 5 }
												]
											}}
										/>
									</Form.Item>
									<Form.Item name="opera2" className={Style.item}>
										<CommonField
											Component={Select}
											props={{
												placeholder: "商品编码",
												options: [
													{ label: "生成商品编码", value: "create" },
													{ label: "清空商品编码", value: "clear" }
												]
											}}
										/>
									</Form.Item>
									<Form.Item name="opera3" className={Style.item}>
										<CommonField
											Component={Select}
											props={{
												placeholder: "批量按款填充",
												options: [
													{ label: "按款填充零售价", value: "retailPrice" },
													{ label: "按款填充成本价", value: "costPrice" },
													{ label: "按款填充市场价I吊牌价", value: "tagPrice" },
													{ label: "按款填充重量", value: "weight" },
													{ label: "按款填充图片", value: "image" },
													{ label: "按款填充商品成分", value: "productIngredients" },
													{ label: "按款填充自定义属性", value: "customAttribute" }
												]
											}}
										/>
									</Form.Item>
								</div>

								<TableEditForm
									form={form}
									name="goodsSku"
									rowKey="key"
									scroll={{ y: `calc(100vh - 250px)` }}
									bordered
									remove={remove}
									columns={goodsColumns}
									pagination={false}
									rowSelection={{
										selectedRowKeys,
										onChange: selectedRowKeys => {
											setSelectedRowKeys(selectedRowKeys);
										}
									}}
								/>
							</Collapse.Panel>
							<Collapse.Panel header={archorList[ARCHOR_LIST_MAP.otherSettings].render()} key="otherSettings">
								<Row gutter={[12, 6]}>
									{/* <Col span={24}>
										<Form.Item label="商品状态" name="status" initialValue={0}>
											<Radio.Group>
												{SPU_STATUS.map(item => (
													<Radio key={item.value} value={item.value}>
														{item.label}
													</Radio>
												))}
											</Radio.Group>
										</Form.Item>
									</Col> */}
									<Col span={24}>
										<Form.Item label="设为跑量商品" name="runningVolumeStatus" initialValue={0}>
											<Radio.Group>
												{YES_NO_NUM_STATUS.map(item => (
													<Radio key={item.value} value={item.value}>
														{item.label}
													</Radio>
												))}
											</Radio.Group>
										</Form.Item>
									</Col>
								</Row>
							</Collapse.Panel>
						</Collapse>
					</Form>
				</div>
			</div>

			{dialogName === "AttrClassifyModal" && (
				<AttrClassifyModal
					attrList={attrList}
					setVisible={setVisible}
					getAttrList={getAttrList}
					oldAttrList={oldAttrList}
					onCancel={() => {
						setDialogName("");
					}}
				/>
			)}
			{dialogName === "ImageErrorModal" && (
				<ImageErrorModal
					onCancel={() => {
						setDialogName("");
					}}
				/>
			)}
			{dialogName === "ProductSynchronizationUpdate" && (
				<ProductSynchronizationUpdateModal
					list={goodSyncList}
					// RefForm={form}
					handleOk={(name, updataList) => {
						if (name === "确定") {
							console.log(updataList);
							const data = form.getFieldsValue();
							form.setFieldsValue({
								goodsSku: data.goodsSku.map(item => {
									const obj = {
										...item
									};
									(updataList || []).forEach(key => {
										const { value } = goodSyncList.find(e => e.prop === key);
										obj[key] = value;
									});
									return obj;
								})
							});
						}
						handleOk(type, false);
						setGoodSyncList([]);
						setDialogName("");
					}}
					onCancel={() => {
						setGoodSyncList([]);
						setDialogName("");
					}}
				/>
			)}
		</CommonDrawer>
	);
};
export default SpuViewModal;
